//
//  NetworkManager.m
//
//  Created by 刘川 on 2018/05/23.
//  Copyright © 2017年 com.YiQiLe. All rights reserved.
//

#import "NetworkManager.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "RequestApiConfig.h"

@implementation NetworkManager

static NSMutableArray *_allSessionTask;

#pragma -mark 初始化 AFHTTPSessionManager

+ (AFHTTPSessionManager *)sharedManager{
    
    static AFHTTPSessionManager *sessionManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        sessionManager = [[AFHTTPSessionManager alloc]init];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
        [sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        sessionManager.requestSerializer.timeoutInterval = 30.f;
        [sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
    });
    return sessionManager;
}

+ (NSMutableArray *)allSessionTask {
    if (!_allSessionTask) {
        _allSessionTask = [[NSMutableArray alloc] init];
    }
    return _allSessionTask;
}

#pragma mark - 开始监听网络
+ (void)networkStatusWithBlock:(networkStatus) networkStatus {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                    networkStatus ? networkStatus(NetworkStatusUnknown) : nil;
                    NSLog(@"未知网络");
                    break;
                case AFNetworkReachabilityStatusNotReachable:
                    networkStatus ? networkStatus(NetworkStatusNotReachable) : nil;
                    NSLog(@"无网络");
                    break;
                case AFNetworkReachabilityStatusReachableViaWWAN:
                    networkStatus ? networkStatus(NetworkStatusReachableViaWWAN) : nil;
                    NSLog(@"手机自带网络");
                    break;
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    networkStatus ? networkStatus(NetworkStatusReachableViaWiFi) : nil;
                    NSLog(@"WIFI");
                    break;
            }
        }];
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    });
}

+ (BOOL)isNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

+ (BOOL)isWWANNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWWAN;
}

+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
}

+ (void)cancelAllRequest {
    @synchronized(self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}

+ (void)cancelRequestWithURL:(NSString *)URL {
    if (!URL) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}

#pragma mark - Get/Post请求
+ (NSURLSessionTask *)requestType:(RequestType) type
                              url:(NSString *) url
                           params:(NSDictionary *) params
                    callbackBlock:(callbackBlock) callbackBlock{
    
    if (!params) return nil;
    
    if (type == RequestTypeGet){
        
        NSURLSessionTask *sessionTask = [[NetworkManager sharedManager] GET:[NSString stringWithFormat:@"%@%@",kApi_Base_Url,url] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
        {
            [[self allSessionTask] removeObject:task];
            callbackBlock ? callbackBlock(responseObject, nil): nil;
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
        {
            [[self allSessionTask] removeObject:task];
            callbackBlock ? callbackBlock(nil, error) : nil;
            
        }];
        sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
        return sessionTask;

    }else if (type == RequestTypePost){
        
        NSURLSessionTask *sessionTask = [[NetworkManager sharedManager] POST:[NSString stringWithFormat:@"%@%@",kApi_Base_Url,url] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
        {
            [[self allSessionTask] removeObject:task];
            callbackBlock ? callbackBlock(responseObject, nil): nil;
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
        {
            [[self allSessionTask] removeObject:task];
            callbackBlock ? callbackBlock(nil, error) : nil;
        }];
        sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
        return sessionTask;
    }
    return nil;
}

#pragma mark - 上传张图片

+ (NSURLSessionTask *)uploadImagesWithURL:(NSString *) URL
                               parameters:(id) parameters
                                     name:(NSString *) name
                                   images:(NSArray<UIImage *> *) images
                                fileNames:(NSArray<NSString *> *) fileNames
                               imageScale:(CGFloat) imageScale
                                imageType:(NSString *) imageType
                                 progress:(httpProgress) progress
                            callbackBlock:(callbackBlock) callbackBlock{

    NSURLSessionTask *sessionTask = [[NetworkManager sharedManager]  POST:URL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSInteger i = 0; i < images.count; i++) {
            // 图片经过等比压缩后得到的二进制文件
            NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
            // 默认图片的文件名, 若fileNames为nil就使用
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *imageFileName = [NSString stringWithFormat:@"%@%ld.%@",str,i,imageType?:@"jpg"];
            [formData appendPartWithFileData:imageData
                                        name:name
                                    fileName:fileNames?[NSString stringWithFormat:@"%@.%@",fileNames[i],imageType?:@"jpg"] : imageFileName
                                    mimeType:[NSString stringWithFormat:@"image/%@",imageType ?: @"jpg"]];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(uploadProgress) : nil;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[self allSessionTask] removeObject:task];
        callbackBlock ? callbackBlock(responseObject,nil) : nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[self allSessionTask] removeObject:task];
       callbackBlock ? callbackBlock(nil, error) : nil;
    }];
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil ;
    return sessionTask;
}

@end
